<template>
  <PageContainer>
    <Header title="选择圈子">
      <view class="hb-h-9 hb-box-content hb-py-2 hb-px-4">
        <TSearch text="搜索" @confirm="handleConfirm"></TSearch>
      </view>
    </Header>
    <view>
      <view class="hb-p-4 hb-pb-0">
        <TmCheckboxGroup v-model="selected">
          <template v-for="v in dataList" :key="v.id">
            <view
              class="hb-p-3 hb-w-full hb-mb-4 hb-rounded-lg hb-flex hb-items-center hb-bg-white hb-box-shadow-base"
            >
              <TmCheckbox :margin="[0, 0, 24, 0]" :size="40" :value="v.id" />
              <TmImage
                class="hb-flex-shrink-0"
                :src="v.avatar"
                :width="80"
                :height="80"
                :round="4"
                @click="handleSelectItem(v)"
              />
              <view
                class="hb-ml-3 hb-flex-1 hb-h-10 hb-flex hb-flex-col hb-justify-between"
                @click="handleSelectItem(v)"
              >
                <TmText _class="hb-font-bold text-overflow-1" :label="v.name" :font-size="32" />
                <TmText
                  :label="v.description"
                  _class="text-overflow-1"
                  color="#969799"
                  :font-size="24"
                />
              </view>
            </view>
          </template>
        </TmCheckboxGroup>
        <Empty v-if="dataList.length === 0" />
      </view>
      <BottomSubmit :submit-btn-label="submitBtnLabel" @submit="handleSelectSubmit" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* selectCircles 选择圈子 */
  import { aiSelectCircleList } from '@/api/contact';
  import { CircleListResult } from '@/api/contact/types';
  import { SelectCircles } from '@/router/types/modules';
  import { isArray } from 'lodash-es';

  const dataList = ref<CircleListResult[]>([]);
  const allData = ref<CircleListResult[]>([]);
  const getDataList = (keyWord?: string) => {
    aiSelectCircleList({ keyWord }).then((res) => {
      dataList.value = res;
      if (!keyWord) allData.value = res;
    });
  };
  getDataList();

  let success: SelectCircles['success'];
  const selected = ref<number[]>([]);
  customOnload<'selectCircles'>((op) => {
    if (isArray(op.selected) && op.selected.length > 0) {
      selected.value = op.selected;
    }
    success = op.success;
  });

  const handleSelectItem = (v: CircleListResult) => {
    if (selected.value.includes(v.id)) {
      selected.value = selected.value.filter((item) => item !== v.id);
    } else {
      selected.value.push(v.id);
    }
  };

  /** 搜索 */
  const handleConfirm = (val: string) => {
    getDataList(val);
  };

  const submitBtnLabel = computed(() => `确认选择（${selected.value.length}）`);

  const handleSelectSubmit = () => {
    success?.(allData.value.filter((item) => selected.value.includes(item.id)));
    navigateBack();
  };
</script>

<style lang="scss" scoped></style>
